import {  Component, EventEmitter, Injector, Output, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { SimpleOrganinzationUnitDto, UserRoleUnitSelectionServiceProxy } from '@shared/service-proxies/service-proxies';
import { ArrayToTreeConverterService } from '@shared/utils/service/array-to-tree-converter.service';
import { TreeDataHelperService } from '@shared/utils/service/tree-data-helper.service';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { TreeNode } from 'primeng/api';
import { ISelectionUnitBackData } from '../workflow-common-interface';



@Component({
    selector: 'selection-unit-box',
    templateUrl: './selection-unit-box.component.html'
})
export class SelectionUnitBoxModalComponent extends AppComponentBase {
    @ViewChild('selectionModal', { static: true }) modal: ModalDirective;
    @Output() selectUnitModalSave: EventEmitter<ISelectionUnitBackData> = new EventEmitter<ISelectionUnitBackData>();

    treeData: TreeNode<SimpleOrganinzationUnitDto>[];
    selectedTreeData: TreeNode<SimpleOrganinzationUnitDto>[] = [];
    
    constructor(
        injector: Injector,
        private _userRoleUnitSelectionServiceProxy:UserRoleUnitSelectionServiceProxy,
        private _arrayToTreeConverterService: ArrayToTreeConverterService,
        private _treeDataHelperService: TreeDataHelperService,
    ) {
        super(injector);
    }

    show(unitIdList:string): void {
        this.selectedTreeData = [];
        this.modal.show();
        this.initData(unitIdList);
    }
    
    setTreeData(permissions: SimpleOrganinzationUnitDto[]) {
        this.treeData = this._arrayToTreeConverterService.createTree(permissions, 'parentId', 'id', null, 'children',
            [{
                target: 'label',
                source: 'displayName'
            }, {
                target: 'expandedIcon',
                value: 'fa fa-folder-open text-warning'
            },
            {
                target: 'collapsedIcon',
                value: 'fa fa-folder text-warning'
            },
            {
                target: 'expanded',
                value: false
            }]);
    }

    setSelectedNodes(unitIds: number[]) {
        unitIds.forEach(unitId=>{
            let item = this._treeDataHelperService.findNode(this.treeData, { data: { id: unitId } });
            if (item) {
                this.selectedTreeData.push(item);
            }
        });
    }

    nodeSelect(e){
        console.log(e.node)
    }

    onNodeUnselect(e){
        let s = this.selectedTreeData;
        console.log(e.node)
    }

    save(): void {
        let ids:string = this.selectedTreeData.map(item=>item.data.id).join(',');
        let names:string = this.selectedTreeData.map(item=>item.data.displayName).join(',');
        this.selectUnitModalSave.emit({
            ids:ids,
            names:names
        })
        this.close();
    }

    clearAllData(){
        this.selectedTreeData = [];
    }

    openAll(){
        this._treeDataHelperService.operateTreeNode(this.treeData,(item)=>{
            item.expanded = true;
        })
    }

    closeAll(){
        this._treeDataHelperService.operateTreeNode(this.treeData,(item)=>{
            item.expanded = false;
        })
    }

    close(): void {
        this.modal.hide();
    }

    private initData(unitIds:string){
        this._userRoleUnitSelectionServiceProxy.getOrganizationUnits().subscribe(res=>{
              let unitArr:number[] = [];
              if (unitIds){
                  unitArr = unitIds.split(',').map(item=>Number(item));
              }
              this.setTreeData(res);
              this.setSelectedNodes(unitArr);
        });
    }

    private expandRecursive(node:TreeNode, isExpand:boolean){
        node.expanded = isExpand;
        if (node.children){
            node.children.forEach( childNode => {
                this.expandRecursive(childNode, isExpand);
            } );
        }
    }

   
}
